package com.cn.wanxi.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * 图片上传，返回所有数据
 */
public class Upload {
    /**
     * 图片上传，返回所有数据
     *
     * @param req
     * @return
     */
    public static String getData(HttpServletRequest req) throws UnsupportedEncodingException {
        FileItemFactory factory = new DiskFileItemFactory();
        // 创建文件上传处理器
        ServletFileUpload upload = new ServletFileUpload(factory);

        // 开始解析请求信息
        List items = null;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        // 对所有请求信息进行判断
        Iterator iter = items.iterator();
        StringBuilder stringBuilder = new StringBuilder();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // 信息为普通的格式
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                String value = item.getString("UTF-8");
                stringBuilder.append(value + "@@");
            }
            // 信息为文件格式
            else {
                String fileName = item.getName();
                System.out.println(fileName);
//                E:\wanxi\step-four\canyin04-0707\web\WEB-INF\lib\aa.aa.aa.jpg
                int index = fileName.lastIndexOf("\\");
                fileName = fileName.substring(index + 1);//得到当前文件的名称
//1.得到图片后，需要讲图片保存到服务器，并返回图片地址
                String savePath = "E:\\wanxi\\step-four\\canyin04-0721/web";//绝对路径，图片保存的路径
                String path = "/loadImg/";//相对路径，主要用于存于数据库
//
                String name = fileName.substring(0, fileName.lastIndexOf("."));
                name = name + new Date().getTime();//增加一个毫秒数,为了保证文件名不重复
                String houzhui = fileName.substring(fileName.lastIndexOf("."));
                fileName = name + houzhui;
                String realPath = path + fileName;
                File derctoryFile = new File(savePath, path);
                if (!derctoryFile.exists()) {
                    derctoryFile.mkdirs();
                }
                File file = new File(derctoryFile, fileName);
                try {
                    item.write(file);
                    item.delete();
                    stringBuilder.append(realPath + "@@");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuilder.toString();
    }
}
